package gw.reportbuilder.nucleo;

import gw.reportbuilder.nucleo.excecao.ExcecaoConexao;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Vladson Pontes
 */
public class Conexao {

    public Conexao() {
    }
    private static String userName;
    private static String passWord;
    private static String hostName;
    private static String dataBase;

    static {
        try {

            Properties props = new Properties();
            InputStream stream = Conexao.class.getClassLoader().getResourceAsStream("gw/reportbuilder/config/connection.properties");

            props.load(stream);

            userName = props.getProperty("user");
            passWord = props.getProperty("password");
            hostName = props.getProperty("hostname");
            dataBase = props.getProperty("database");
        } catch (IOException ex) {
            Logger.getLogger(Conexao.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static Connection getConnection() throws ExcecaoConexao, IOException {
        Properties jdbcProperties = new Properties();

        String driver = "org.postgresql.Driver";
        String url = "jdbc:postgresql://" + hostName + "/" + dataBase + "?charSet=LATIN1";
        String login = userName;
        String password = passWord;
        Connection con = null;
        try {

            jdbcProperties.put("user", userName);
            jdbcProperties.put("password", passWord);
            jdbcProperties.put("logUnclosedConnections", "true");

            Class.forName(driver).newInstance();
            con = DriverManager.getConnection(url, login, password);

        } catch (ClassNotFoundException ex) {
            throw new ExcecaoConexao("Classe do driver nao encontrada - " + ex.getMessage());
        } catch (SQLException ex) {
            throw new ExcecaoConexao(ex.getMessage());
        } catch (InstantiationException ex) {
            throw new ExcecaoConexao(ex.getMessage());
        } catch (IllegalAccessException ex) {
            throw new ExcecaoConexao(ex.getMessage());
        }

        return con;

    }
}